package ranab.server;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import ranab.io.IoUtils;

/**
 * It sends the user typed message and prints the input message
 */
public 
class MessageEchoer {

    private Socket mSoc;

    /**
     * Set the socket from where to will get message and write ours.
     */
    public MessageEchoer(Socket soc) {
        mSoc = soc;    
    }

    /**
     * Start message transfer
     */
    public void start() throws Exception {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = mSoc.getInputStream();
            out = mSoc.getOutputStream();
            
            Thread th1 = new Thread(new Copier(in, System.out));
            Thread th2 = new Thread(new Copier(System.in, out));
            
            th1.start();
            th2.start();
            
            th1.join();
            th2.join();
        }
        finally {
            IoUtils.close(in);
            IoUtils.close(out);
        }
        
    }
    
    
    /**
     * Inner class to copy in from one stream to another
     */
    private class Copier implements Runnable {
        InputStream in;
        OutputStream out;
        
        public Copier(InputStream in, OutputStream out) {
            this.in = in;
            this.out = out;
        }
        
        public void run() {
            try {
                IoUtils.copy(in, out, 1);
            }
            catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
